using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using GamePlay.Framework.Events;
using GamePlay.Features.Shared;

namespace GamePlay.Features.Core
{
    /// <summary>
    /// 游戏核心管理器，控制游戏流程和状态
    /// </summary>
    public class GameManager : MonoBehaviour
    {
        #region 单例实现

        private static GameManager _instance;

        public static GameManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    GameObject obj = new GameObject("GameManager");
                    _instance = obj.AddComponent<GameManager>();
                    DontDestroyOnLoad(obj);
                }
                return _instance;
            }
        }

        private void Awake()
        {
            if (_instance != null && _instance != this)
            {
                Destroy(gameObject);
                return;
            }

            _instance = this;
            DontDestroyOnLoad(gameObject);

            // 初始化状态
            _gameState = GameState.None;

            // 注册事件
            RegisterEvents();
        }

        private void OnDestroy()
        {
            // 取消注册事件
            UnregisterEvents();
        }

        #endregion

        #region 字段和属性

        // 游戏状态
        private GameState _gameState;

        // 游戏模式
        [SerializeField] private int _gameMode = 0;

        // 当前关卡
        [SerializeField] private string _currentLevel = string.Empty;

        // 游戏开始时间
        private float _gameStartTime;

        // 游戏暂停前的时间
        private float _pauseTime;

        // 游戏是否暂停
        private bool _isPaused;

        // 调试模式
        [SerializeField] private bool _debugMode = false;

        // 公开属性
        public GameState State => _gameState;
        public int GameMode => _gameMode;
        public string CurrentLevel => _currentLevel;
        public bool IsPaused => _isPaused;
        public float GameTime => _isPaused ? _pauseTime - _gameStartTime : Time.time - _gameStartTime;

        #endregion

        #region 游戏状态枚举

        public enum GameState
        {
            None,       // 初始状态
            Loading,    // 加载中
            Menu,       // 菜单中
            Playing,    // 游戏中
            Paused,     // 已暂停
            GameOver    // 游戏结束
        }

        #endregion

        #region Unity生命周期

        private void Update()
        {
            // 游戏状态管理逻辑
            switch (_gameState)
            {
                case GameState.Playing:
                    // 游戏中的更新逻辑
                    break;

                case GameState.Paused:
                    // 暂停状态下的逻辑
                    break;

                    // 其他状态...
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 启动游戏
        /// </summary>
        /// <param name="gameMode">游戏模式</param>
        /// <param name="levelName">关卡名称</param>
        public void StartGame(int gameMode, string levelName)
        {
            if (_gameState == GameState.Playing)
            {
                LogWarning("游戏已经在运行中");
                return;
            }

            _gameMode = gameMode;
            _currentLevel = levelName;

            // 更新状态
            ChangeState(GameState.Loading);

            // 加载场景
            StartCoroutine(LoadLevelAsync(levelName));
        }

        /// <summary>
        /// 暂停游戏
        /// </summary>
        public void PauseGame()
        {
            if (_gameState != GameState.Playing)
            {
                LogWarning("只有在游戏运行中才能暂停");
                return;
            }

            _pauseTime = Time.time;
            _isPaused = true;
            Time.timeScale = 0;

            ChangeState(GameState.Paused);

            // 触发暂停事件
            EmitEvent(new GamePauseArgs { IsPaused = true });
        }

        /// <summary>
        /// 恢复游戏
        /// </summary>
        public void ResumeGame()
        {
            if (_gameState != GameState.Paused)
            {
                LogWarning("游戏未处于暂停状态");
                return;
            }

            _isPaused = false;
            Time.timeScale = 1;

            ChangeState(GameState.Playing);

            // 触发恢复事件
            EmitEvent(new GamePauseArgs { IsPaused = false });
        }

        /// <summary>
        /// 结束游戏
        /// </summary>
        /// <param name="isWin">是否胜利</param>
        /// <param name="score">得分</param>
        public void EndGame(bool isWin, int score)
        {
            if (_gameState != GameState.Playing && _gameState != GameState.Paused)
            {
                LogWarning("游戏未处于可结束状态");
                return;
            }

            // 确保时间正常
            if (_isPaused)
            {
                Time.timeScale = 1;
                _isPaused = false;
            }

            // 计算游戏持续时间
            float gameDuration = Time.time - _gameStartTime;

            // 更新状态
            ChangeState(GameState.GameOver);

            // 触发游戏结束事件
            EmitEvent(new GameEndArgs
            {
                IsWin = isWin,
                Score = score,
                Duration = gameDuration
            });
        }

        /// <summary>
        /// 返回主菜单
        /// </summary>
        public void ReturnToMenu()
        {
            // 确保时间正常
            if (_isPaused)
            {
                Time.timeScale = 1;
                _isPaused = false;
            }

            // 更新状态
            ChangeState(GameState.Menu);

            // 加载主菜单场景
            SceneManager.LoadScene("MainMenu");
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 异步加载关卡
        /// </summary>
        private IEnumerator LoadLevelAsync(string levelName)
        {
            // 获取异步加载操作
            AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(levelName);

            // 防止加载完成后自动激活场景
            asyncLoad.allowSceneActivation = false;

            // 等待加载完成
            while (asyncLoad.progress < 0.9f)
            {
                yield return null;
            }

            // 激活场景
            asyncLoad.allowSceneActivation = true;

            while (!asyncLoad.isDone)
            {
                yield return null;
            }

            // 重置游戏参数
            _gameStartTime = Time.time;
            _isPaused = false;

            // 更新状态
            ChangeState(GameState.Playing);

            // 触发游戏开始事件
            EmitEvent(new GameStartArgs
            {
                GameMode = _gameMode,
                LevelName = _currentLevel
            });
        }

        /// <summary>
        /// 改变游戏状态
        /// </summary>
        private void ChangeState(GameState newState)
        {
            GameState oldState = _gameState;
            _gameState = newState;

            if (_debugMode)
            {
                Debug.Log($"[GameManager] 游戏状态变更: {oldState} -> {newState}");
            }
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        private void RegisterEvents()
        {
            // 注册需要监听的事件
        }

        /// <summary>
        /// 取消注册事件
        /// </summary>
        private void UnregisterEvents()
        {
            // 取消注册已监听的事件
        }

        /// <summary>
        /// 发送事件
        /// </summary>
        private void EmitEvent<T>(T eventArgs) where T : EventArgs
        {
            EventManager.Instance.RaiseEvent(this, eventArgs);
        }

        /// <summary>
        /// 打印调试日志
        /// </summary>
        private void Log(string message)
        {
            if (_debugMode)
            {
                Debug.Log($"[GameManager] {message}");
            }
        }

        /// <summary>
        /// 打印警告日志
        /// </summary>
        private void LogWarning(string message)
        {
            if (_debugMode)
            {
                Debug.LogWarning($"[GameManager] {message}");
            }
            else
            {
                Debug.LogWarning($"[GameManager] {message}");
            }
        }

        #endregion
    }
}